package io.github.center.config.filter;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 抽象过滤器
 *
 * @author haijun
 * @version 1.0.0
 * @email "1424132610@qq.com"
 * @date 2024.10.19 11:15
 * @since 1.0.0
 */
public abstract class AbstractFilter extends OncePerRequestFilter {

    /**
     * ant风格表达式匹配器
     */
    private final AntPathMatcher matcher = new AntPathMatcher();

    /**
     * 获取到需要忽略的路径
     *
     * @return the ignores
     * @since 1.0.0
     */
    protected abstract List<String> getIgnores();

    /**
     * 不需要进行拦截的路径，默认放掉swagger相关
     *
     * @param request request
     * @return boolean boolean
     * @since 1.0.0
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        List<String> ignores = getIgnores();
        if (CollectionUtils.isEmpty(ignores)) {
            return true;
        }
        //ant风格表达式进行匹配请求路径
        return ignores.stream().anyMatch(p -> matcher.match(p, path)) || !StringUtils.hasText(path);
    }
}
